import * as Koa from "koa";
import * as path from "path";
import * as serve from "koa-static";
import * as Router from "koa-router";
import * as cors from 'koa2-cors';
import * as bodyParser from 'koa-bodyparser';
import webRouter from './router';

let router = new Router();
const app = new Koa();

app.use(bodyParser());
app.use(cors({
    origin:function (ctx) {
        const {origin} = ctx.request.header;
        const allowHost = ['http://localhost:3001','http://localhost:8080'];
        for(let i=0;i<allowHost.length;i++){
            if(`${origin}`===allowHost[i]){
                return allowHost[i];
            }
        }
        return false;
    },
    allowMethods:['GET','POST'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'],
}));

app.use(serve(path.resolve('./static')));

webRouter(router);

const host = 'localhost';
const port = 3002;

app.listen((function(){
    console.log('http://'+host+':'+port);
    return port;
})());


app.use(router.routes()).use(router.allowedMethods());